package com.xxwy.protocal;

import com.xxwy.simple.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * @author wy
 * @date 2020/3/4 23:09
 */
public class NettyClient {
  public static void main(String[] args) {

//创建事件循环组
    NioEventLoopGroup loopGroup = new NioEventLoopGroup();
    try {


      //创建客户端
      Bootstrap bootstrap = new Bootstrap();

      //设置参数
      bootstrap.group(loopGroup)
          .channel(NioSocketChannel.class)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
              //加入编码器
              socketChannel.pipeline().addLast(new XxwyEncoder());
              socketChannel.pipeline().addLast(new XxwyClientHandler());
            }
          });
      //启动连接服务器
      //关于ChannelFuture，要分析，涉及到netty的异步模型
      ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();
      channelFuture.channel().closeFuture().sync();

    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      loopGroup.shutdownGracefully();
    }


  }
}
